﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using Sharp.DataTransferObject;
using Sharp.Infrastructure;
using Sharp.Infrastructure.WebApiClient;
using Sharp.Portal.AdminLTE;
using Sharp.Portal.Mvc;
using Sharp.Portal.Mvc.Models;
using Sharp.ServiceContracts;
using Sharp.WebBooter.Areas.Platform.Models;
// ReSharper disable Mvc.ViewNotResolved

namespace Sharp.WebBooter.Areas.Platform.Controllers
{
    [Authorize]
    [AutomaticTemplate]
    public class OrgController : SharpController
    {
        #region Index

        public async Task<ActionResult> Index()
        {
            List<OrgIndexViewModel> newOrgList = new List<OrgIndexViewModel>();
            IEnumerable<OrgDTO> list;

            using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
            {
                list = await proxy.Channel.GetOrgsWithCount();
            }

            Build(list, newOrgList, null);

            return View(new OrgIndexViewModel() {Data = newOrgList});
        }

        public static void Build(IEnumerable<OrgDTO> table, List<OrgIndexViewModel> node, Guid? parentValue)
        {
            var rows = table.Where(x => x.ParentId == parentValue).OrderBy(x => x.OrderIndex);
            foreach (var row in rows)
            {
                var _node = new OrgIndexViewModel();
                _node = row.To<OrgIndexViewModel>();
                if (row.ParentId == null)
                {
                    _node.Itemclass = $"treegrid-{row.Id}";
                }
                else
                {
                    _node.Itemclass = $"treegrid-{row.Id} treegrid-parent-{row.ParentId}";
                }


                node.Add(_node);

                Build(table, node, row.Id);
            }
        }

        #endregion

        internal static void Build(IEnumerable<OrgDTO> table, zTreeNode node, Guid? parentValue)
        {
            var rows = table.Where(x => x.ParentId == parentValue).OrderBy(x => x.OrderIndex);
            foreach (var row in rows)
            {
                var _node = new zTreeNode
                {
                    Name = row.Title,
                    Id = row.Id.ToString(),
                    ParentId = row.ParentId == null ? row.ParentId.ToString() : null,
                    Raw = row
                };

                node.Children.Add(_node);
                node.IsParent = node.Children.Any();

                Build(table, _node, row.Id);
            }
        }

        internal static void Build(IEnumerable<MasterDataSimpleDTO> table, zTreeNode node, string parentcode)
        {
            var rows = table.Where(x => x.ParentCode == parentcode).OrderBy(x => x.OrderIndex);
            foreach (var row in rows)
            {
                var _node = new zTreeNode
                {
                    Name = row.Name,
                    Id = row.Id.ToString(),
                    ParentId = row.ParentCode,
                    Raw = row
                };

                node.Children.Add(_node);
                node.IsParent = node.Children.Any();

                Build(table, _node, row.Code);
            }
        }

        public async Task<ActionResult> Details(Guid? id)
        {
            return await Edit(id.Value);
        }
        [Permission("新增", 1, "003002001")]
        public async Task<ActionResult> Create()
        {
            var model = new OrgViewModel
            {
                ParentIdDataSource = new zTreeNode(),
                AreaCodeDataSource=new zTreeNode()
            };
            IEnumerable<OrgDTO> allOrgs;
            using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
            {
                model.OrgLevelList = await proxy.Channel.GetOrgLevelList();
                allOrgs = await proxy.Channel.GetOrgs();
            }
            var areaList = Sharp.Portal.Platform.GetMasterData("AdministrativeDivision");
            Build(areaList, model.AreaCodeDataSource, null);

            Build(allOrgs, model.ParentIdDataSource, null);

            return View(model);
        }

        internal static async Task<zTreeNode> RootNode()
        {
            IEnumerable<OrgDTO> allOrgs;
            using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
            {
                allOrgs = await proxy.Channel.GetOrgs();
            }
            var rootNode = new zTreeNode()
            {
                Name = ".",
                Checked = null
            };


            var builder = new TreeBuilder<Guid, OrgDTO>
            {
                ChangeData = (p, treeNode) =>
                {
                    treeNode.Name = p.Title;
                    treeNode.Id = p.Id.ToString();
                    treeNode.IsParent = allOrgs.Any(x => x.ParentId == p.Id);
                    treeNode.Raw = p;
                }
            };
            builder.Build(allOrgs, rootNode, null);

            return rootNode;

        }

        [Permission("编辑", 2, "003002002")]
        public async Task<ActionResult> Edit(Guid id)
        {
            OrgViewModel model;
            IEnumerable<OrgDTO> allOrgs;
            using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
            {
                model = proxy.Channel.GetOrgInfo(id).To<OrgViewModel>();
                model.OrgLevelList = await proxy.Channel.GetOrgLevelList();
                model.ParentIdDataSource = new zTreeNode();
                model.AreaCodeDataSource = new zTreeNode();

                allOrgs = await proxy.Channel.GetOrgs();
            }

            var areaList = Sharp.Portal.Platform.GetMasterData("AdministrativeDivision");
            Build(areaList, model.AreaCodeDataSource, "0");

            Build(allOrgs, model.ParentIdDataSource, null);
            return View(model);
        }

        
        public ActionResult Save(OrgDTO vm)
        {
            if (vm == null)
            {
                return this.JsonNet(new Result() {Err = "提交数据出错。"});
            }
            using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
            {
                var res = proxy.Channel.SaveOrg(vm);
                res.RedirectToUrl = Url.Action("Index");

                return this.JsonNet(res);
            }
        }

        [Permission("删除", 3, "003002003")]
        
        public ActionResult Delete(Guid[] ids)
        {
            using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
            {
                var res = proxy.Channel.DeleteOrgs(ids);
                res.RedirectToUrl = Url.Action("Index");

                return this.JsonNet(res);
            }
        }

    }
}